<template>
  <div class="health-box" style="padding-right: 12px">
    <template v-if="activeKey == 2">
      <div class="manual-tip">
        <img class="tip-img" src="@/assets/health/ai-normal.png" alt="" />
        <span class="tip-content"
          >人工随访记录仅对医生开放查看权限，此记录主要用于辅助医生记录与患者沟通时的随访相关内容。</span
        >
      </div>
    </template>
    <a-tabs v-model:activeKey="activeKey" type="card" @change="changeTab">
      <a-tab-pane :key="1" tab="系统随访" />
      <a-tab-pane :key="2" tab="人工随访" />
    </a-tabs>
    <div>
      <template v-if="activeKey == 1">
        <a-table
          size="small"
          :columns="state.column"
          :dataSource="state.table"
          :loading="state.tableLoading"
          :pagination="paginate"
          :scroll="{ y: 'calc(100vh - 350px)' }"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'planTime'">
              {{ record.planTime ? dayjs(record.planTime).format('YYYY年MM月DD日 HH:mm') : '' }}
            </template>
            <template v-else-if="column.dataIndex == 'diseaseType'">
              <span v-if="record.diseaseType == 'checkAfter'">检后管理</span>
              <span v-if="record.diseaseType == 'weightLose'">减重管理</span>
            </template>
            <template v-else-if="column.dataIndex === 'isRead'">
              <span style="color: #00b42a" v-if="record.isRead">
                <CheckCircleFilled two-tone-color="#00B42A" />
                已填写
              </span>
              <span style="color: #f53f3f" v-if="!record.isRead">
                <ExclamationCircleFilled two-tone-color="#F53F3F" />
                未填写
              </span>
            </template>
            <template v-else-if="column.dataIndex === 'action'">
              <a-button type="link" @click="followInfo(record)"> 查看详情 </a-button>
            </template>
          </template>
        </a-table>
      </template>
      <template v-else-if="activeKey == 2">
        <div style="display: flex; justify-content: space-between">
          <Condition
            :condition="condition"
            :btns="['search', 'reset']"
            @search="searchHandle"
            @reset="reset"
          />
          <a-button type="primary" @click="addFollowInfo('')">新建随访记录</a-button>
        </div>
        <a-table
          size="small"
          :columns="state.columnManual"
          :dataSource="state.table"
          :loading="state.tableLoading"
          :pagination="pagination"
          @change="paginationChange"
          :scroll="{ y: 'calc(100vh - 400px)' }"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'action'">
              <a-button type="link" @click="addFollowInfo(record)"> 查看详情 </a-button>
            </template>
            <template v-else-if="column.dataIndex === 'content'">
              <div class="content">{{ record.content }}</div>
            </template>
          </template>
        </a-table>
      </template>
    </div>
  </div>
  <FollowInfo ref="followInfoRef" />

  <!-- 新增随访记录 -->
  <a-modal v-model:open="open" title="人工随访记录" :width="800" :mask-closable="false">
    <a-form
      layout="vertical"
      class="remarkForm"
      ref="followFormDataRef"
      :model="followFormData"
      :disabled="followState == 'edit'"
    >
      <a-form-item
        label="人工随访记录仅对医生开放查看权限，此记录主要用于辅助医生记录与患者沟通时的随访相关内容。"
        name="followCntent"
        :rules="[{ required: true, message: '请输入随访内容', whitespace: true }]"
      >
        <a-textarea
          v-model:value="followFormData.followCntent"
          style="width: 100%"
          :rows="10"
          :maxlength="500"
          :show-count="true"
        />
      </a-form-item>
    </a-form>
    <template #footer>
      <template v-if="followState == 'add'">
        <a-button @click="open = false">取消</a-button>
        <a-button type="primary" @click="saveFollowForm">保存</a-button>
      </template>
    </template>
  </a-modal>
</template>

<script setup lang="ts">
import Condition from '@/components/ConditionSearch/index.vue'
import { ref, reactive, onMounted } from 'vue'
import FollowInfo from './followInfo.vue'
import {
  getPatientFollowUp,
  getPatientArtificial,
  savePatientArtificial
} from '@/api/patientMana/index'
import { CheckCircleFilled, ExclamationCircleFilled } from '@ant-design/icons-vue'
import dayjs from 'dayjs'
import { message } from 'ant-design-vue'
const state = reactive({
  column: [
    {
      title: '随访日期',
      key: 'planTime',
      align: 'left',
      dataIndex: 'planTime'
    },
    {
      title: '随访问卷',
      key: 'itemName',
      align: 'left',
      dataIndex: 'itemName'
    },
    {
      title: '问卷状态',
      key: 'isRead',
      align: 'left',
      dataIndex: 'isRead'
    },
    {
      title: '来源',
      key: 'diseaseType',
      align: 'left',
      dataIndex: 'diseaseType'
    },
    {
      title: '操作',
      key: 'action',
      align: 'left',
      dataIndex: 'action'
    }
  ],
  columnManual: [
    {
      title: '随访日期',
      key: 'createTime',
      align: 'left',
      dataIndex: 'createTime'
    },
    {
      title: '随访医生',
      key: 'followDoctorName',
      align: 'left',
      dataIndex: 'followDoctorName'
    },
    {
      title: '随访内容',
      key: 'content',
      align: 'left',
      dataIndex: 'content'
    },
    {
      title: '操作',
      key: 'action',
      align: 'left',
      dataIndex: 'action'
    }
  ],
  table: [],
  tableLoading: false
})
const activeKey = ref(1)
const patEmpi = ref('')
const paginate = ref({
  // defaultPageSize: 5
  current: 1,
  pageSize: 10,
  onChange: (current, size) => {
    paginate.value.current = current
    paginate.value.pageSize = size
  },
  showQuickJumper: true
})

const pagination = ref<any>({
  current: 1,
  total: 0,
  pageSize: 10,
  showSizeChanger: true,
  pageSizeOptions: ['10', '20', '50', '100'],
  showQuickJumper: true
})

const open = ref<boolean>(false)
const followState = ref('')

const condition = ref([
  {
    title: '',
    dataIndex: 'doctorName',
    type: 'input',
    value: '',
    placeholder: '请输入随访医生',
    style: {
      width: '225px'
    }
  },
  {
    title: '',
    dataIndex: 'followTime',
    type: 'dayRange',
    value: [],
    format: 'YYYY-MM-DD',
    placeholder: ['开始日期', '结束日期'],
    style: { width: '300px' }
  }
])

const planTaskId = ref('')
const init = (id, taskId) => {
  state.tableLoading = true
  patEmpi.value = id
  planTaskId.value = taskId
  getDataLIst()
}

const changeTab = (key) => {
  state.tableLoading = true
  activeKey.value = key
  getDataLIst()
}

const getDataLIst = () => {
  if (activeKey.value == 1) {
    getPatientFollowUp({ empi: patEmpi.value })
      .then((res) => {
        state.tableLoading = false
        state.table = res.data

        if (planTaskId.value) {
          const planTaskData = res.data.find((item) => item.taskId == planTaskId.value)

          followInfo(planTaskData)
        }
      })
      .catch(() => {
        state.tableLoading = false
      })
  } else {
    const obj = condition.value.reduce((c, v) => {
      if (v.value || v.value === 0 || v.value === false) {
        if (v.dataIndex == 'followTime') {
          return Object.assign(c, {
            start: v.value.length ? dayjs(v.value[0]).format('YYYY-MM-DD 00:00:00') : '',
            end: v.value.length ? dayjs(v.value[1]).format('YYYY-MM-DD 23:59:59') : ''
          })
        } else {
          return Object.assign(c, { [v.dataIndex]: v.value })
        }
      } else {
        return c
      }
    }, {})
    getPatientArtificial({
      ...obj,
      empi: patEmpi.value,
      page: pagination.value.current,
      limit: pagination.value.pageSize
    }).then((res) => {
      state.tableLoading = false
      state.table = res.data.list
      pagination.value.total = res.data.total
    })
  }
}

const followInfoRef = ref()
const followInfo = (data) => {
  followInfoRef.value.init(data)
}

const followFormData = reactive({ followCntent: '' })
const followFormDataRef = ref()
const addFollowInfo = (data) => {
  open.value = true
  followFormData.followCntent = ''
  followState.value = data ? 'edit' : 'add'

  if (data) {
    followFormData.followCntent = data.content
  }
}

const saveFollowForm = () => {
  followFormDataRef.value
    .validate()
    .then(() => {
      console.log(followFormData)

      const param = {
        empi: patEmpi.value,
        content: followFormData.followCntent
      }
      savePatientArtificial(param).then((res) => {
        message.success('保存成功')
        open.value = false
        state.tableLoading = true
        getDataLIst()
      })
    })
    .catch(() => {})
}

const searchHandle = () => {
  pagination.value.current = 1
  state.tableLoading = true
  getDataLIst()
}

const reset = () => {
  pagination.value.current = 1
  pagination.value.pageSize = 10
  condition.value.map((v) => {
    if (v.type === 'select') {
      v.value = undefined
    } else if (v.type === 'followTime') {
      v.value = []
    } else {
      v.value = ''
    }
  })
  state.tableLoading = true
  getDataLIst()
}

const paginationChange = (page: any) => {
  pagination.value = { ...page }
  state.tableLoading = true
  getDataLIst()
}

defineExpose({
  init
})
</script>

<style lang="less" scoped>
.title-box {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  height: 32px;
  margin: 0 0 10px;
  font-weight: 600;
  line-height: 32px;
  color: #1d2129;

  .title-item-left {
    font-size: 18px;
    font-weight: 600;
  }

  .text-icon {
    display: inline-block;
    width: 3px;
    height: 16px;
    margin-right: 8px;
    line-height: 32px;
    background: #165dff;
  }
}

.manual-tip {
  display: flex;
  align-items: center;
  height: 40px;
  padding: 0 16px;
  margin-bottom: 8px;
  background: #e8f3ff;
  border-radius: 2px;

  .tip-img {
    width: 16px;
    height: 16px;
    margin-right: 8px;
  }

  .tip-content {
    font-size: 14px;
    font-weight: 400;
    color: #1d2129;
  }
}

.content {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>

<style>
.remarkForm .ant-form-item {
  margin-bottom: 0;

  .ant-input-disabled,
  .ant-input[disabled] {
    color: #1d2129;
  }
}
</style>
